package com.localdemo.checkforloopholes.check.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

@Slf4j
@Service
public class NvdDataService {

    private static final String NVD_JSON_GZ_URL = "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-recent.json.gz";
    private static final String LOCAL_JSON_PATH = "nvdcve-1.1-recent.json";

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 定时任务：每天凌晨1点执行
     */
    public void downloadAndParseNvdData() {
        try {
            log.info("开始下载NVD漏洞数据...");
            // 下载并解压
            try (InputStream in = new java.util.zip.GZIPInputStream(new URL(NVD_JSON_GZ_URL).openStream());
                 FileOutputStream out = new FileOutputStream(LOCAL_JSON_PATH)) {
                IOUtils.copy(in, out);
            }
            log.info("NVD漏洞数据下载解压完成，文件路径: {}", LOCAL_JSON_PATH);

            // 解析JSON文件
            parseNvdJson(LOCAL_JSON_PATH);

        } catch (Exception e) {
            log.error("NVD数据下载或解析失败", e);
        }
    }

    /**
     * 解析NVD JSON文件，打印部分漏洞信息
     */
    private void parseNvdJson(String jsonFilePath) throws Exception {
        log.info("开始解析NVD JSON文件...");
        JsonNode root = objectMapper.readTree(new java.io.File(jsonFilePath));

        // TODO:
        //  处理解析逻辑等
    }
}
